/*
Copyright (c) 2009 Gonzalo Huerta-Canepa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

package cl.huerta.pdf
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	
	public class PDFContext
	{
	    /**
	     * Modi
	     *
	     * @var integer 0 = file | 1 = string
	     */
	    protected var _mode:Number = 0;
	    
		protected var file:*;
		public var bbuffer:ByteArray;
		public var buffer:String;
		public var offset:Number;
		public var length:Number;
		
		protected var _stream:FileStream;
		public function get stream():FileStream {
			return this._stream;
		}
		
		public var stack:Array;

		// Constructor
		public function PDFContext(f:*)
		{
			this.file = f;
			if (f is String)
				this._mode = 1;
			else if (f is File) {
				this._stream = new FileStream();
				this._stream.open(f, FileMode.READ);
			} else 
				this._stream = f;
			this.bbuffer = new ByteArray();
			this.reset();
		}
	
		// Optionally move the file
		// pointer to a new location
		// and reset the buffered data
		public function reset(pos:Number = NaN, l:Number = 100):void {
		    if (this._mode == 0) {
	        	if (!isNaN(pos))
	        		this._stream.position = pos;
	    		else
	    			pos = this._stream.position;
        		this.bbuffer.clear();
	    		if (l>0) {
	    			this.buffer = _stream.readMultiByte(Math.min(this.stream.bytesAvailable,l), "windows-1252");
	        		this._stream.position = pos;
		    		_stream.readBytes(this.bbuffer, 0, Math.min(this.stream.bytesAvailable,l));
	    		}
		    	else {
	    			this.buffer = '';
		    	}
	    		this.length = this.bbuffer.length;
	    		if (this.length < l)
	                this.increaseLength(l - this.length);
		    } else {
		        this.buffer = this.file;
		        this.bbuffer.clear();
		        this.bbuffer.writeUTF(this.buffer);
		        this.length = this.buffer.length;
		    }
			this.offset = 0;
			this.stack = new Array();
		}
	
		// Make sure that there is at least one
		// character beyond the current offset in
		// the buffer to prevent the tokenizer
		// from attempting to access data that does
		// not exist
		public function ensureContent():Boolean {
			if (this.offset >= this.length - 1) {
				return this.increaseLength();
			} else {
				return true;
			}
		}
	
		// Forcefully read more data into the buffer
		public function increaseLength(l:Number=100):Boolean {
			if (this._mode == 0 && this._stream.bytesAvailable == 0) {
				return false;
			} else if (this._mode == 0) {
			    var totalLength:Number = this.length + Math.min(l, this._stream.bytesAvailable);
			    do {
	    			var pos:Number = this._stream.position;
	    			this.buffer += _stream.readMultiByte((totalLength-this.length), "windows-1252");
	        		this._stream.position = pos;
		    		_stream.readBytes(this.bbuffer, this.length, Math.min(this.stream.bytesAvailable,l));
	                this.length = this.bbuffer.length;
	            } while ((this.length != totalLength) && (this._stream.bytesAvailable > 0));
				
				return true;
			} else {
		        return false;
			}
		}

	}
}